package com.fvision.camera.manager;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.fvision.camera.bean.DataPaket;
import com.fvision.camera.bean.FileBean;
import com.fvision.camera.iface.ICameraStateChange;
import com.fvision.camera.iface.IGetPlackBack;
import com.fvision.camera.iface.IProgressBack;
import com.fvision.camera.iface.ISmallVideoBack;
import com.fvision.camera.util.CameraStateUtil;
import com.fvision.camera.util.Cmd_Const;
import com.fvision.camera.util.LogUtils;
import com.huiying.cameramjpeg.UvcCamera;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by zoulequan on 2019/3/23.
 */

public class VideoDownloadManager {
    private static VideoDownloadManager _instance;
    public static final int WHAT_RECORD_SMALL_VIDEO_END = 1;
    public static final int WHAT_GET_BACK_LIST = 10;
    private boolean recordLock = false;
    private boolean getPlackBackLock = false;
    private float loadProgress = 0;
    private String filePath;
    private String downloadDir = Environment.getExternalStorageDirectory() + "/uvccameramjpeg/VIDEO/";

    private ISmallVideoBack mIsmallVideoBack;
    private IGetPlackBack mIGetPlackBack;
    public static final int MOB = 5;
    private ICameraStateChange mICameraStateChange = new ICameraStateChange() {
        @Override
        public void stateChange() {
            if (!CmdManager.getInstance().getCurrentState().isCam_rec_state()) {
                endSmallVideoOp();
                CameraStateIml.getInstance().delListener(mICameraStateChange);
            }
        }
    };
    boolean isUseDuration = false;
    long duration = 0;
    private ICameraStateChange cmdICameraStateChange = new ICameraStateChange() {
        @Override
        public void stateChange() {
            LogUtils.d("small video 录像状态改变 " + CmdManager.getInstance().getCurrentState().isCam_rec_state());
            if (CmdManager.getInstance().getCurrentState().isCam_rec_state()) {
                CameraStateIml.getInstance().delListener(cmdICameraStateChange);
                if (isUseDuration) {
                    LogUtils.d("small video 开启倒计时" + duration / 1000 + "秒");
                    mHandler.sendEmptyMessageDelayed(WHAT_RECORD_SMALL_VIDEO_END, duration);
                }
            } else {
                CmdManager.getInstance().recToggle();
            }
            recordLock = true;
        }
    };

    private ICameraStateChange getBackListStateChange = new ICameraStateChange() {
        @Override
        public void stateChange() {
            LogUtils.d("backlist 录像状态改变 " + CmdManager.getInstance().getCurrentState().isCam_rec_state());
            if (!CmdManager.getInstance().getCurrentState().isCam_rec_state()) {
                getBackList1();
            }
        }
    };

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_RECORD_SMALL_VIDEO_END:
                    if (CmdManager.getInstance().getCurrentState().isCam_rec_state()) {
                        CmdManager.getInstance().recToggle();//停止录制
                    } else {
                        if (mIsmallVideoBack != null) {
                            mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_RECORD_STOP, "录制小视频被终止");
                        }
                        recordLock = false;
                        return;
                    }
                    CameraStateIml.getInstance().addListener(mICameraStateChange);
                    break;
                case WHAT_GET_BACK_LIST:

                    break;
            }
        }
    };

    public static VideoDownloadManager getInstance() {
        if (_instance == null) {
            _instance = new VideoDownloadManager();
        }
        return _instance;
    }

    public boolean recordSmallVideo(final boolean isUseDuration, final long duration, ISmallVideoBack back) {
        mIsmallVideoBack = back;
        if (duration > 30000 && isUseDuration) {
            if (back != null) {
                back.fail(Cmd_Const.SMALL_VIDEO_DURATION_TOO_LONG, "时长不能超过30秒");
            }
            recordLock = false;
            return false;
        }

        if (duration < 5000 && isUseDuration) {
            if (back != null) {
                back.fail(Cmd_Const.SMALL_VIDEO_DURATION_TOO_SMALL, "时长不能小于5秒");
            }
            recordLock = false;
            return false;
        }

        if (recordLock) {
            if (back != null) {
                back.fail(Cmd_Const.SMALL_VIDEO_RECORDING, "正在录制...");
            }
            return false;
        }

        if (!UvcCamera.getInstance().isInit()) {
            if (back != null) {
                back.fail(Cmd_Const.SMALL_VIDEO_UNDETECTED_RECORDER, "未检测到行车记录仪");
            }
            recordLock = false;
            return false;
        }

        if (!UvcCamera.getInstance().cmd_fd_error.equals("Success")) {
            if (back != null) {
                back.fail(Cmd_Const.SMALL_VIDEO_CMD_UNINIT, "指令文件未初始化");
            }
            recordLock = false;
            return false;
        }
        if (CmdManager.getInstance().getCurrentState().isCam_rec_state()) {//如果正在录像
            LogUtils.d("small video 关闭录像");
            CmdManager.getInstance().recToggle();
        } else {//如果没在录像
            LogUtils.d("small video 开启录像");
            CmdManager.getInstance().recToggle();
        }
        LogUtils.d("small video 等待录像开启...");
        this.isUseDuration = isUseDuration;
        this.duration = duration;
        CameraStateIml.getInstance().addListener(cmdICameraStateChange);
        return true;
    }

    public boolean startSmallVideo(final long duration, ISmallVideoBack back) {
        return recordSmallVideo(true, duration, back);
    }

    public boolean startSmallVideo(ISmallVideoBack back) {
        return recordSmallVideo(false, -1, back);
    }

    public void endSmallVideo() {
        mHandler.sendEmptyMessage(WHAT_RECORD_SMALL_VIDEO_END);
    }

    private void endSmallVideoOp() {
//        LogUtils.d("small video 结束");
//       // int fileSize = CmdManager.getInstance().getFileCount(Cmd_Const.FILE_TYPE_VIDEO_FRONT);
//       // List<String> nameList = new ArrayList<>();
//        ArrayList<String> files = CmdManager.getInstance().getVideoFront(null);
//        String name=null;
//        if (files != null && files.size() > 0) {
//            for (String fileName : files) {
// //               nameList.add(fileName);
//                if(fileName.contains("ch0")){
//                    name = fileName;
//                }
//            }
//        }
//        LogUtils.d("small video 获取到最后一个录像的文件名"+name);
//        if(!CmdManager.getInstance().getCurrentState().isCam_rec_state()){
//            CmdManager.getInstance().recToggle();
//        }
//        if(name!=null){
//            downloadFileThread(name,Cmd_Const.CMD_FILE_TYPE_DCIM,null);
//        }else {
//            if(mIsmallVideoBack!=null){
//                mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OTHER,"没有获取到前录视频");
//            }
//        }
//        recordLock = false;
    }

    /**
     * 下载
     *
     * @param fileName
     * @param fileType CMD_FILE_TYPE_DCIM CMD_FILE_TYPE_LOCK CMD_FILE_TYPE_PHOTO
     * @param back
     */
    public void downloadFileThread(final String fileName, final int fileType, final IProgressBack back) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                downloadFile(fileName, fileType, back);
            }
        }).start();
    }

    public void downloadFileThread(final String fileName, final IProgressBack back) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                downloadFile(fileName, back);
            }
        }).start();
    }

    public void downloadFileThread(final String fileName, final String feName, final int num, final IProgressBack back) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (fileName != null && feName != null && back != null) {
                    downloadFile(fileName, feName, num, back);
                }
            }
        }).start();
    }

    private void downloadFile(String fPath, String feName, int num, IProgressBack back) {
        loadProgress = 0;
        CmdManager.getInstance().getVideoDurationTime(feName);
//        UvcCamera.getInstance().stopPreview();
        long startTime = System.currentTimeMillis();
        LogUtils.d("small video 开始下载 ");
        long length_k = 0;
        long length_kb = 0;
        long startDounloadTime = System.currentTimeMillis();
        LogUtils.d(" start download time=" + System.currentTimeMillis() + " item.fileName" + fPath);
        try {
            LogUtils.d("small video filePath " + fPath);
            File video = new File(fPath);
            if (video.exists()) {
                LogUtils.e("文件已存在 " + fPath);
                if (mIsmallVideoBack != null) {
                    mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_FILE_EXIXT, filePath);
                }
                if (back != null) {
                    back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_FILE_EXIXT, filePath);
                }
                recordLock = false;
                return;
            }
            Log.e("sss下载中....", "" + UvcCamera.getInstance().cmd_fd_error);
            int filesize = CmdManager.getInstance().getVideoZhenTime(num); //获取文件大小
            Log.e("帧图片+fileSize", "" + filesize);
            if (filesize < 1) {
                LogUtils.e("downfile 下载文件失败，打开错误 " + fPath);
                if (mIsmallVideoBack != null) {
                    mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OPEN_FAIL, "downfile 下载失败，打开文件错误");
                }
                if (back != null) {
                    back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_OPEN_FAIL, "downfile 下载失败，打开文件错误");
                }
                recordLock = false;
                return;
            }
            length_k = filesize;
            length_kb = length_k / 1024;
            int nu = 8;//一次获取的大小
            long endDataSize = length_k % (1024 * nu);
            long count = -1;
            int offset = 0;
            if (endDataSize != 0) {
                count = length_kb / nu + 1;
            } else {
                count = length_kb / nu;
            }
            LogUtils.d("downfile length_k " + length_k + " length_kb " + length_kb + " count " + count + " endDataSize " + endDataSize);

            RandomAccessFile raf = null;

            raf = new RandomAccessFile(fPath, "rw");
            for (int i = 0; i < count; i++) {
                LogUtils.d("downfile small video " + i + "  " + count);
                if (mIsmallVideoBack != null) {
                    mIsmallVideoBack.downloadProgress(i * 100 / count);
                }
                if (back != null) {
                    float progress = i * 100 / count;
                    if (progress != loadProgress) {
                        loadProgress = progress;
                        back.onProgress(loadProgress);
                    }
                }
                long dataSize = -1;
                if (i < count - 1) {
                    dataSize = nu * 1024;
                } else {
                    if (endDataSize == 0) {
                        dataSize = nu * 1024;
                    } else {
                        dataSize = endDataSize;
                    }
                }
                DataPaket paket = CmdManager.getInstance().getVideoFileData(i, (int) dataSize);
                Log.e("paket+dataSize", "" + (int) dataSize);
                if (paket == null) {
                    LogUtils.d("downfile 下载失败,获取数据失败");
//                    boolean isClose = CmdManager.getInstance().closeDownloadZhenFile();
//                    Log.e("获取帧图片流", "是否关闭+paket == null" + isClose);
                    video.delete();
                    if (mIsmallVideoBack != null) {
                        mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_DOWNLOAD_FAIL, "下载失败,获取数据失败");
                    }
                    if (back != null) {
                        back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_DOWNLOAD_FAIL, "下载失败,获取数据失败");
                    }
                    recordLock = false;
                    return;
                }
                LogUtils.d("downfile  offset " + i + " paket.length " + paket.length);
                raf.seek(offset);
                offset += paket.length;
                raf.write(paket.data);
//            if (autoLine) {
//                raf.write("/n".getBytes());
//            }
            }
            if (mIsmallVideoBack != null) {
                mIsmallVideoBack.success(fPath);
            }
            if (back != null) {
                long endTime = System.currentTimeMillis();
//                LogUtils.d(" 下载时长:" + ((endTime - startTime) / 1000));
                back.onSuccess(fPath);
            }
            raf.close();
//            if (!isClose) {
//                CmdManager.getInstance().closeDownloadZhenFile();
//            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            if (mIsmallVideoBack != null) {
                mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OTHER, "下载失败: FileNotFoundException " + e.getMessage());
            }
            if (back != null) {
                back.onFail(0, "下载失败:FileNotFoundException " + e.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (mIsmallVideoBack != null) {
                mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OTHER, "下载失败: IOException " + e.getMessage());
            }
            if (back != null) {
                back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_OTHER, "下载失败: IOException " + e.getMessage());
            }
        } finally {
//            boolean isClose = CmdManager.getInstance().closeDownloadZhenFile();
//            Log.e("finally+获取帧图片流", "是否关闭" + isClose);
//            UvcCamera.getInstance().startPreview();
            recordLock = false;

        }
    }


    private void downloadFile(String fileName, int fileType, IProgressBack back) {
        loadProgress = 0;
        UvcCamera.getInstance().stopPreview();
        long startTime = System.currentTimeMillis();
        LogUtils.d("small video 开始下载 ");
        long length_k = 0;
        long length_kb = 0;
        long startDounloadTime = System.currentTimeMillis();
        Log.e("downloadFile", " start download time=" + System.currentTimeMillis() + " item.fileName" + fileName);
        try {
            filePath = downloadDir + fileName;
            LogUtils.d("small video filePath " + filePath);
            File video = new File(filePath);
            if (video.exists()) {
                video.delete();
            }
            if (video.exists()) {
                LogUtils.e("文件已存在 " + filePath);
                if (mIsmallVideoBack != null) {
                    mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_FILE_EXIXT, filePath);
                }
                if (back != null) {
                    back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_FILE_EXIXT, filePath);
                }
                UvcCamera.getInstance().startPreview();
                recordLock = false;
                return;
            } else {
                video.createNewFile();
            }
            int filesize = CmdManager.getInstance().openReadFile(fileType, fileName);
            if (filesize < 1) {
                LogUtils.e("downfile 下载文件失败，打开错误 " + fileName);
                if (mIsmallVideoBack != null) {
                    mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OPEN_FAIL, "downfile 下载失败，打开文件错误");
                }
                if (back != null) {
                    back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_OPEN_FAIL, "downfile 下载失败，打开文件错误");
                }
                UvcCamera.getInstance().startPreview();
                recordLock = false;
                return;
            }
            length_k = filesize;
            length_kb = length_k / 1024;
            int num = 8;//一次获取的大小
            long endDataSize = length_k % (1024 * num);
            long count = -1;
            int offset = 0;
            if (endDataSize != 0) {
                count = length_kb / num + 1;
            } else {
                count = length_kb / num;
            }
            Log.e("downfile length_k ", "downfile length_k " + length_k + " length_kb " + length_kb + " count " + count + " endDataSize " + endDataSize);

            RandomAccessFile raf = null;

            raf = new RandomAccessFile(filePath, "rw");
            for (int i = 0; i < count; i++) {
                LogUtils.d("downfile small video " + i + "  " + count);
                if (mIsmallVideoBack != null) {
                    mIsmallVideoBack.downloadProgress(i * 100 / count);
                }
                if (back != null) {
                    float progress = i * 100 / count;
                    if (progress != loadProgress) {
                        loadProgress = progress;
                        back.onProgress(loadProgress);
                    }
                }
                long dataSize = -1;
                if (i < count - 1) {
                    dataSize = num * 1024;
                } else {
                    if (endDataSize == 0) {
                        dataSize = num * 1024;
                    } else {
                        dataSize = endDataSize;
                    }
                }
                DataPaket paket = CmdManager.getInstance().getFileData(i, (int) dataSize);
                if (paket == null) {
                    LogUtils.e("downfile 下载失败,获取数据失败");
                    CmdManager.getInstance().closeReadFile();
                    video.delete();
                    if (mIsmallVideoBack != null) {
                        mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_DOWNLOAD_FAIL, "下载失败,获取数据失败");
                    }
                    if (back != null) {
                        back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_DOWNLOAD_FAIL, "下载失败,获取数据失败");
                    }
                    UvcCamera.getInstance().startPreview();
                    recordLock = false;
                    return;
                }
                LogUtils.d("downfile  offset " + i + " paket.length " + paket.length);
                raf.seek(offset);
                offset += paket.length;
                raf.write(paket.data);
//            if (autoLine) {
//                raf.write("/n".getBytes());
//            }
            }
            if (mIsmallVideoBack != null) {
                mIsmallVideoBack.success(filePath);
            }
            if (back != null) {
                long endTime = System.currentTimeMillis();
                LogUtils.d(" 下载时长:" + ((endTime - startTime) / 1000));
                back.onSuccess(filePath);
            }
            raf.close();
            CmdManager.getInstance().closeDownloadFile();
            LogUtils.d("small video download time=" + ((System.currentTimeMillis() - startDounloadTime) / 1000));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            if (mIsmallVideoBack != null) {
                mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OTHER, "下载失败: FileNotFoundException " + e.getMessage());
            }
            if (back != null) {
                back.onFail(0, "下载失败:FileNotFoundException " + e.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (mIsmallVideoBack != null) {
                mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OTHER, "下载失败: IOException " + e.getMessage());
            }
            if (back != null) {
                back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_OTHER, "下载失败: IOException " + e.getMessage());
            }
        } finally {
            UvcCamera.getInstance().startPreview();
            recordLock = false;
        }
    }

    private void downloadFile(String fileName, IProgressBack back) {
        loadProgress = 0;
        UvcCamera.getInstance().stopPreview();
        long startTime = System.currentTimeMillis();
        LogUtils.d("small video 开始下载 ");
        long length_k = 0;
        long length_kb = 0;
        long startDounloadTime = System.currentTimeMillis();
        LogUtils.d(" start download time=" + System.currentTimeMillis() + " item.fileName" + fileName);
        try {
            filePath = downloadDir + fileName;
            LogUtils.d("small video filePath " + filePath);
            File video = new File(filePath);
            if (video.exists()) {
                video.delete();
            }
            if (video.exists()) {
                LogUtils.e("文件已存在 " + filePath);
                if (mIsmallVideoBack != null) {
                    mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_FILE_EXIXT, filePath);
                }
                if (back != null) {
                    back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_FILE_EXIXT, filePath);
                }
                UvcCamera.getInstance().startPreview();
                recordLock = false;
                return;
            } else {
                video.createNewFile();
            }
            int filesize = CmdManager.getInstance().openReadFiles(fileName);
            if (filesize < 1) {
                LogUtils.e("downfile 下载文件失败，打开错误 " + fileName);
                if (mIsmallVideoBack != null) {
                    mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OPEN_FAIL, "downfile 下载失败，打开文件错误");
                }
                if (back != null) {
                    back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_OPEN_FAIL, "downfile 下载失败，打开文件错误");
                }
                UvcCamera.getInstance().startPreview();
                recordLock = false;
                return;
            }
            length_k = filesize;
            length_kb = length_k / 1024;
            int num = 8;//一次获取的大小
            long endDataSize = length_k % (1024 * num);
            long count = -1;
            int offset = 0;
            if (endDataSize != 0) {
                count = length_kb / num + 1;
            } else {
                count = length_kb / num;
            }
            LogUtils.d("downfile length_k " + length_k + " length_kb " + length_kb + " count " + count + " endDataSize " + endDataSize);

            RandomAccessFile raf = null;

            raf = new RandomAccessFile(filePath, "rw");
            for (int i = 0; i < count; i++) {
                LogUtils.d("downfile small video " + i + "  " + count);
                if (mIsmallVideoBack != null) {
                    mIsmallVideoBack.downloadProgress(i * 100 / count);
                }
                if (back != null) {
                    float progress = i * 100 / count;
                    if (progress != loadProgress) {
                        loadProgress = progress;
                        back.onProgress(loadProgress);
                    }
                }
                long dataSize = -1;
                if (i < count - 1) {
                    dataSize = num * 1024;
                } else {
                    if (endDataSize == 0) {
                        dataSize = num * 1024;
                    } else {
                        dataSize = endDataSize;
                    }
                }
                DataPaket paket = CmdManager.getInstance().getFileData(i, (int) dataSize);
                if (paket == null) {
                    LogUtils.e("downfile 下载失败,获取数据失败");
                    CmdManager.getInstance().closeReadFile();
                    video.delete();
                    if (mIsmallVideoBack != null) {
                        mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_DOWNLOAD_FAIL, "下载失败,获取数据失败");
                    }
                    if (back != null) {
                        back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_DOWNLOAD_FAIL, "下载失败,获取数据失败");
                    }
                    UvcCamera.getInstance().startPreview();
                    recordLock = false;
                    return;
                }
                LogUtils.d("downfile  offset " + i + " paket.length " + paket.length);
                raf.seek(offset);
                offset += paket.length;
                raf.write(paket.data);
//            if (autoLine) {
//                raf.write("/n".getBytes());
//            }
            }
            if (mIsmallVideoBack != null) {
                mIsmallVideoBack.success(filePath);
            }
            if (back != null) {
                long endTime = System.currentTimeMillis();
                LogUtils.d(" 下载时长:" + ((endTime - startTime) / 1000));
                back.onSuccess(filePath);
            }
            raf.close();
            CmdManager.getInstance().closeDownloadFile();
            LogUtils.d("small video download time=" + ((System.currentTimeMillis() - startDounloadTime) / 1000));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            if (mIsmallVideoBack != null) {
                mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OTHER, "下载失败: FileNotFoundException " + e.getMessage());
            }
            if (back != null) {
                back.onFail(0, "下载失败:FileNotFoundException " + e.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (mIsmallVideoBack != null) {
                mIsmallVideoBack.fail(Cmd_Const.SMALL_VIDEO_OTHER, "下载失败: IOException " + e.getMessage());
            }
            if (back != null) {
                back.onFail(Cmd_Const.DOWNLOAD_FILE_ERROR_OTHER, "下载失败: IOException " + e.getMessage());
            }
        } finally {
            UvcCamera.getInstance().startPreview();
            recordLock = false;
        }
    }

    public void setDownloadDir(String downloadDir) {
        this.downloadDir = downloadDir;
    }

    public String getDownloadDir() {
        return downloadDir;
    }

    /**
     * 获取回放列表
     *
     * @return
     */
    public void getBackList(IGetPlackBack back) {
        mIGetPlackBack = back;
        if (!UvcCamera.getInstance().isInit()) {
            if (back != null) {
                back.onFail(101, "未连接到记录仪");
            }
            return;
        }
        getPlackBackLock = true;
        CameraStateIml.getInstance().addListener(getBackListStateChange);

        if (CmdManager.getInstance().getCurrentState().isCam_rec_state()) {//如果正在录像
            LogUtils.d("backlist 关闭录像");
            boolean ret = CmdManager.getInstance().recToggle();
            if (!ret && back != null) {
                back.onFail(104, "关闭录像失败 " + UvcCamera.getInstance().cmd_fd_error);
                LogUtils.e("backlist", "关闭录像失败 " + UvcCamera.getInstance().cmd_fd_error);
            }
            getPlackBackLock = false;
        } else {
            getBackList1();
        }
    }

    private void getBackList1() {
        int fileSize = CmdManager.getInstance().getCurrentState().getFile_index();
        if (fileSize < 1) {
            if (mIGetPlackBack != null) {
                mIGetPlackBack.onFail(102, "文件数小于1 " + fileSize);
            }
            if (!CmdManager.getInstance().getCurrentState().isCam_rec_state()) {
                CmdManager.getInstance().recToggle();
            }
            getPlackBackLock = false;
            return;
        }
        byte[] files = new byte[fileSize * 6];
        int ret = CmdManager.getInstance().sendCommand(42, files.length, files);//打开文件
        if (ret < 0) {
            if (mIGetPlackBack != null) {
                mIGetPlackBack.onFail(103, "指令发送失败 " + UvcCamera.getInstance().cmd_fd_error);
            }
            if (!CmdManager.getInstance().getCurrentState().isCam_rec_state()) {
                CmdManager.getInstance().recToggle();
            }
            getPlackBackLock = false;
            return;
        }
        LogUtils.d("" + CameraStateUtil.bytesToHexString(files));
        List<FileBean> mFileList = new ArrayList<>();
        for (int i = 0; i * Cmd_Const.FILE_BYTE_SIZE < files.length; i++) {
            byte[] item = new byte[Cmd_Const.FILE_BYTE_SIZE];
            System.arraycopy(files, i * Cmd_Const.FILE_BYTE_SIZE, item, 0, item.length);
            FileBean file = byte2FileBean(item);
            file.fileIndex = i + 1;
            if (file.year <= 1980) {//过滤 1979年的视频文件
                continue;
            }
            //          LogUtils.d("files file.dayTime "+file.dayTime +" format "+CameraStateUtil.longToString(file.dayTime,null));
            mFileList.add(file);
        }
        if (!CmdManager.getInstance().getCurrentState().isCam_rec_state()) {
            CmdManager.getInstance().recToggle();
        }
        if (mFileList.size() > 1) {
            if (mIGetPlackBack != null) {
                mIGetPlackBack.onSuccess(mFileList);
            }
        } else {
            if (mIGetPlackBack != null) {
                mIGetPlackBack.onFail(105, "没有回放文件");
            }
        }
    }

    private FileBean byte2FileBean(byte[] filebyte) {
        if (filebyte.length != Cmd_Const.FILE_BYTE_SIZE) {
            //           LogUtils.e(" filebyte.length != Cmd_Const.FILE_BYTE_SIZE ");
            if (mIGetPlackBack != null) {
                mIGetPlackBack.onFail(150, "filebyte.length != Cmd_Const.FILE_BYTE_SIZE");
            }
            return null;
        }
        //       LogUtils.d("filebyte "+CameraStateUtil.bytesToHexString(filebyte));
        FileBean file = new FileBean();
        StringBuffer fileName = new StringBuffer();

        short file_type_num = 0;
        short file_year_month_day = 0;
        short file_hour_minute_second = 0;

        byte[] byte_type_num = new byte[2];
        byte[] byte_year_month_day = new byte[2];
        byte[] byte_hour_minute_second = new byte[2];

        System.arraycopy(filebyte, 0, byte_type_num, 0, byte_type_num.length);
        System.arraycopy(filebyte, 2, byte_year_month_day, 0, byte_year_month_day.length);
        System.arraycopy(filebyte, 4, byte_hour_minute_second, 0, byte_hour_minute_second.length);

        file_type_num = CameraStateUtil.bytesToShort(byte_type_num, 0);
        file_year_month_day = CameraStateUtil.bytesToShort(byte_year_month_day, 0);
        file_hour_minute_second = CameraStateUtil.bytesToShort(byte_hour_minute_second, 0);

        file.year = (file_year_month_day >> 9) + 1980;
        file.month = (file_year_month_day >> 5) & 0xF;
        file.day = file_year_month_day & 0x1F;
        //(finfo.ftime>>11) , (finfo.ftime>>5)&0x3F , ((finfo.ftime)&0x1F)*2
        file.hour = (file_hour_minute_second >> 11) & 0x1f;
        file.minute = (file_hour_minute_second >> 5) & 0x3F;
        file.sencond = ((file_hour_minute_second) & 0x1F) * 2;

        //       LogUtils.d("file.hour "+file.hour+" minute "+file.minute + " sencond "+file.sencond + " file_hour_minute_second "+file_hour_minute_second);
        Log.e("file_type_num", "\n" + file_type_num);
        if ((file_type_num & 0x1000) > 1) {//加锁
            if ((file_type_num & 0x2000) > 1) {
                fileName.append("LOB");
                file.fileType = Cmd_Const.FILE_TYPE_LOCK;
            } else {
                fileName.append("LOK");
                file.fileType = Cmd_Const.FILE_TYPE_LOCK;
            }
        } else if ((file_type_num & 0x8000) > 1) {//视频
            fileName.append("MOV");
            file.fileType = Cmd_Const.FILE_TYPE_VIDEO;
        } else if ((file_type_num & 0x2000) > 1) {
            fileName.append("MOB");
            file.fileType = MOB; //后录 5
            Log.e("mob", "" + fileName.toString());
        } else if ((file_type_num & 0x4000) > 1) {//图片
            fileName.append("PHO");
            file.fileType = Cmd_Const.FILE_TYPE_PICTURE;
        } else {
            fileName.append("OTHER");
        }

        fileName.append("" + CameraStateUtil.numFormat(file_type_num & 0xfff));//序号

        Calendar calendar = Calendar.getInstance();
        calendar.set(file.year, file.month - 1, file.day, file.hour, file.minute, file.sencond);
        file.dayTime = calendar.getTimeInMillis();
//        String timeStr = file.year+"_"+file.month+"_"+file.day+"_"+file.hour+"_"+file.minute+"_"+file.sencond+"_";

        //  fileName.append(CameraStateUtil.longToString(calendar.getTimeInMillis(),"_mm分ss秒"));//"HH时_mm分ss秒"

        if ((file_type_num & 0x4000) > 1) {//后缀
            fileName.append(".jpg");
        } else {
            fileName.append(".AVI");
        }

        file.fileName = fileName.toString();
        Log.e("fileName", "\n" + file.fileName);
        return file;
    }
}
